<template>
  <div>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="100px" style="width: 500px">

      <el-form-item label="产品名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="产品类型" prop="typeid">
        <el-select v-model="ruleForm.typeid" placeholder="请选择产品类型">
          <el-option v-for="type in types" :label=type.typename :value=type.id ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="产品规格" prop="size">
        <el-input v-model="ruleForm.size"></el-input>
      </el-form-item>

      <el-form-item label="产品介绍" prop="description">
        <el-input v-model="ruleForm.description" type="textarea"></el-input>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      types:null,
      ruleForm: {
        name: '',
        typeid:'',
        size:'',
        description:''
      },
      rules: {
        name: [
          { required: true, message: '产品名不能为空', trigger: 'blur' }
        ],
        typeid:[
          { required: true, message: '必须选择一个类型', trigger: 'change' }
        ],
        size:[
          { required: true, message: '产品规格不能为空', trigger: 'change' }
        ],
        description: [
          {max:200,message:'最多不超过200个字符',trigger: 'change'}
        ]
      },
    };
  },created() {
    axios.get('http://localhost:8081/producttype/findAll/1/100').then(
        (response) => {
          this.types = response.data.content;
        }
    )
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('http://localhost:8081/product/add',this.ruleForm).then((response)=>{
            if(response.data == "success"){
              this.success();
              this.$router.push("/productList");
            }else{
              this.failed();
            }
          })
        } else {
          this.failed();
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    success() {
      this.$message({
        message: '添加成功!',
        type: 'success'
      });
    },
    failed() {
      this.$message.error('添加失败，请检查内容是否正确或稍后再试!');
    }
  }
}
</script>